import 'dart:ffi';

import 'package:eplorex/dao/conversation_dao.dart';
import 'package:eplorex/im/im_sdk_client.dart';
import 'package:eplorex/infra/websocket_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:eplorex/models/message/chat_message_type.dart' as types;
import 'package:provider/provider.dart';
import '../../models/bo/UnReadMessageCounter.dart';
import '../../models/message/message.dart';
import 'message_converstion_cell.dart';
import 'message_notification_box.dart';
import 'convlist_page.dart';

class MessageSubPage extends StatefulWidget {
  const MessageSubPage({super.key});

  @override
  State<MessageSubPage> createState() => _MessageSubPageState();
}

class _MessageSubPageState extends State<MessageSubPage> {
  var currentNetStatus = WebsocketUtils.netStatusNotifier.value;
  late Future<List<ConversationItem>?> _convItemList;
  List<ConversationItem>? _convItems;

  @override
  void initState() {
    _convItemList = ConversationDao.getConversations();
    IMSdkClient.registerCallback(onMessage);

  }


  @override
  void dispose() {
    super.dispose();
    IMSdkClient.unRegisterCallback(onMessage);
  }

  void onMessage(dynamic message){
    types.Message realMessage= message;
    ConversationItem? recievedItem= _convItems?.firstWhere((element) => element.partnerId==int.tryParse(realMessage.author.uid));
    if(recievedItem!=null){
      recievedItem.unreadCnt= recievedItem.unreadCnt==null ? 1: recievedItem.unreadCnt!+1;
      if(realMessage.type ==MessageType.text){
        recievedItem.lastMsg=(realMessage as types.TextMessage).text;
      }
    }else{

    }
    Provider.of<UnReadMessageCounter>(context,listen: false).addUnRead(0,1);
    setState(() {

    });
  }



  @override
  Widget build(BuildContext context) {
    final cid= Provider.of<UnReadMessageCounter>(context);
    return Container(
      margin:const EdgeInsets.all(10),
      child: FutureBuilder(
        future: _convItemList,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child:CircularProgressIndicator(),
            );
          }
          _convItems = _convItems ?? snapshot?.data;
          try{
            var  convItem = _convItems?.firstWhere((element) => element.cid==cid.cid);
            if(convItem!=null){
              convItem.unreadCnt=cid.unreadValue + convItem.unreadCnt!;
            }
          }catch(e){

          }
          return RefreshIndicator(
              onRefresh: _onRefresh,
              child: ListView.builder(
                  itemCount: (2 + _convItems!.length),
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return headWidget();
                    }
                    if (index == 1) {
                      return const SizedBox(
                        height: 10,
                      );
                    }
                    return _item(index - 2, _convItems![index - 2]);
                  }));
        },
      ),
    );
  }

  Widget _item(int index, ConversationItem item) {
    return SwipeActionCell(
      ///这个key是必要的
      key: ValueKey(index),
      trailingActions: <SwipeAction>[
        SwipeAction(
            nestedAction: SwipeNestedAction(
              title: "确认删除",
            ),
            title: "删除",
            onTap: (CompletionHandler handler) async {
              ///true 代表将会执行动画，等待动画结束才更新状态
              await handler(true);
              ConversationItem? convItem = _convItems?[index];
              ConversationDao.deleteConv(convItem!.cid);
              _convItems?.removeAt(index);
              // setState(() {
              //
              // });
            },
            color: Colors.red),
        SwipeAction(
            title: item.topRank > 0 ? "取消置顶" : "置顶",
            onTap: (CompletionHandler handler) async {
              handler(false);
              ConversationItem? convItem = _convItems?[index];
              _convItems?.removeAt(index);
              // 取消置顶
              if (item.topRank > 0) {
                _convItems?.insert(_topRankCnt(), convItem!);
              } else {
                // 随便给一个就行了，为了渲染
                _convItems?.insert(0, convItem!);
              }

              ConversationDao.topRankConv(convItem!.cid, item.topRank <= 0)
                  .then((value) {
                item.topRank = value;
                setState(() {});
              });
            },
            color: Colors.grey),
      ],
      child: MessageConversationCell(
        cid: item.cid,
        senderId: item.senderId!,
        partnerId: item.partnerId!,
        lastMsg: item.lastMsg,
        convName: item.convName,
        convUrl: item.convUrl,
        lastOnlineTime: item.lastOnlineTime,
        unreadCnt: item.unreadCnt ?? 0 ,
      ),
    );
  }

  Future<void> _onRefresh() async {
    await Future.delayed(Duration(seconds: 1), () {
      if (currentNetStatus != NetStatus.connected &&
          currentNetStatus != NetStatus.reconnected) {
        IMSdkClient.initSDK();
        IMSdkClient.login();
      }
    });
  }

  int _topRankCnt() {
    int cnt = 0;
    _convItems?.forEach((element) {
      if (element.topRank > 0) {
        cnt++;
      } else {
        return;
      }
    });
    return cnt;
  }

  Widget headWidget() {
    return Container(
      height: 100,
      color: Colors.white,
      // margin: EdgeInsets.only(bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          MessageNotificationBox(
            title: "评论&赞",
            icon: 'assets/like_icon.png',
            routePath: '/message/notification/like',
          ),
          MessageNotificationBox(
            title: "粉丝",
            icon: 'assets/fans_icon.png',
            routePath: '/message/notification/contact',
          ),
          MessageNotificationBox(
            title: "收藏",
            icon: 'assets/collection_icon.png',
            routePath: '/message/notification/collected',
          ),
        ],
      ),
    );
  }
}
